﻿using System;
using System.Linq;

namespace Cartoons.Books.Model
{
    public class CollectionPropertyAnyFilter : BookFilter
    {
        private string text;
        public CollectionPropertyAnyFilter(string propertyName, string text)
            : base(propertyName)
        {
            this.text = text;
        }

        protected override bool IsMatch(Book book)
        {
            var collectionProperty = typeof(Book).GetProperty(propertyName.Split('.')[0]).GetValue(book, null) as Array;
            if (collectionProperty == null)
                return false;

            foreach (var el in collectionProperty)
                if (el.GetType().GetProperty(propertyName.Split('.')[1]).GetValue(el, null).ToString().ToLower().StartsWith(text.ToLower()))
                    return true;

            return false;
        }
    }
}
